package com.atguigu.srb.sms.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.guli.common.util.RandomUtils;
import com.atguigu.guli.common.util.RegexValidateUtils;
import com.atguigu.srb.base.exception.SrbException;
import com.atguigu.srb.base.result.ResponseEnum;
import com.atguigu.srb.base.util.HttpUtils;
import com.atguigu.srb.base.util.SrbAssert;
import com.atguigu.srb.sms.config.SmsProperties;
import com.atguigu.srb.sms.feign.CoreClient;
import com.atguigu.srb.sms.service.SmsService;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
@EnableConfigurationProperties(SmsProperties.class) //表示当前组件类对象创建时 需要先初始化SmsProperties对象
public class SmsServiceImpl implements SmsService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    CoreClient coreClient;

    @Override
    public void sendSms(String mobile, Integer type) {
        //1.手机号码格式校验：正则表达式
        SrbAssert.assertTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);
        //在之前的core模块中 对于手机的重复注册的判断我们采用的是 当其type=1 注册时 校验手机号是否已经存在与数据库中
        Map<String, Object> result = coreClient.isUsed(mobile).getData();
        //调用了熔断降级 返回注册失败
        SrbAssert.assertNotTrue(CollectionUtils.isEmpty(result),ResponseEnum.ALIYUN_SMS_ERROR);
        //手机号码重复注册校验
        SrbAssert.assertNotTrue(!(Boolean)(result.get("flag")),ResponseEnum.MOBILE_EXIST_ERROR);
        //2.手机号码发送频率：
        // 一分钟内不能重复获取
        String timeLimitKey = "sms:limit:"+type+":"+mobile;
        String countLimitKey = "sms:count:"+type+":"+mobile;
        SrbAssert.assertNotTrue(stringRedisTemplate.hasKey(timeLimitKey),ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR);
        //一天内只能获取5条
        if (stringRedisTemplate.hasKey(countLimitKey)) {
            String countStr = stringRedisTemplate.opsForValue().get(countLimitKey);
            SrbAssert.assertNotTrue(Integer.parseInt(countStr)>=5,ResponseEnum.ALIYUN_SMS_DAY_LIMIT_CONTROL_ERROR);
        }else {
            // 数据不存在 初始化为0 并设置过期时间
            stringRedisTemplate.opsForValue().set(countLimitKey,"0",24,TimeUnit.HOURS);
        }

        //3.生成验证码发送短信
        String code = RandomUtils.getSixBitRandom();
//        sendMessage(mobile, code);

        //4.更新手机号码获取验证码的频率
        //缓存验证码到redis中：使用type区分验证码使用的类型
        stringRedisTemplate.opsForValue().set("sms:code:"+type+":"+mobile,code,2,TimeUnit.MINUTES);
        //更新验证码发送的次数
        //若手机号第一次获取验证码  increment次数默认为0+1
        stringRedisTemplate.opsForValue().increment(countLimitKey);
        //使用手机号码拼接key 缓存一个过期时间为1分钟的数据
        stringRedisTemplate.opsForValue().set(timeLimitKey,"limit",1, TimeUnit.MINUTES);
    }

    //调用第三方接口实现发送短信的业务方法
//    @Resource
//    SmsProperties smsProperties;
    public void sendMessage(String mobile, String code) {
        //服务器地址
//        String host = smsProperties.getHost();
        String host = SmsProperties.HOST;
        //资源路径
        String path = SmsProperties.PATH;
        //请求方式
        String method = SmsProperties.METHOD;
        //在短信平台购买服务时的唯一id
        String appcode = SmsProperties.APPCODE;
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //请求参数：
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", mobile);
        querys.put("content", "【智能云】您的验证码是" + code + "。如非本人操作，请忽略本短信");


        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            String resultJson = EntityUtils.toString(response.getEntity(), "UTF-8");
            Map map = JSON.parseObject(resultJson, Map.class);
            String resultCode = map.get("error_code").toString();
            if (!"0".equals(resultCode)) {
                //短信发送失败
                System.out.println("短信发送失败：" + resultJson);
                throw new SrbException(ResponseEnum.ALIYUN_SMS_ERROR);
            }
            //短信发送成功
            System.out.println("短信发送成功：" + resultJson);
        } catch (Exception e) {
//            e.printStackTrace();
            throw new SrbException(ResponseEnum.ALIYUN_SMS_ERROR);
        }
    }
}
